package cn.fbs.service.core;

import cn.fbs.dao.dm.DMCodeCategoryTypeMapper;
import cn.fbs.dao.dm.DMImageInfoMapper;
import cn.fbs.dao.dm.DMQbCategoryConnectionMapper;
import cn.fbs.model.TImageInfo;
import cn.fbs.param.ImageParam;
import cn.fbs.service.AssignService;
import cn.fbs.service.CategoryService;
import cn.fbs.util.imageshort.FileUtil;
import cn.fbs.vo.QueryPhotoVo;
import cn.fbs.vo.TImageItemVo;
import cn.fbs.vo.TProductInfoVo;
import lombok.SneakyThrows;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@Log
public class ImageService {

    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY = 100;
    private static final Long KEEP_ALIVE_TIME = 5L;
    @Value("${resource.locations}")
    private String resourceLocations;
    @Value(("${compressRatio}"))
    private Integer compressRatio;
    @Value(("${maxJoinNum}"))
    private int maxJoinNum;
    @Autowired
    private DMImageInfoMapper imageInfoMapper;
    @Autowired private DMCodeCategoryTypeMapper categoryTypeMapper;
    @Autowired private CategoryService categoryService;
    @Autowired private DMQbCategoryConnectionMapper connectionMapper;
    @Autowired private AssignService assignService;

    public List<TImageInfo> queryPhotoByParam(QueryPhotoVo photoVo) {
        return imageInfoMapper.queryPhotoByParam(photoVo);
    }

    @Transactional(rollbackFor = Exception.class)
    public String updateZCImage(ImageParam uploadParam) throws IOException {
        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        TImageInfo imageInfo = new TImageInfo();
        imageInfo.setUpdateDate(new Date());
        BeanUtils.copyProperties(uploadParam, imageInfo);
//        String fileName = generatorFileName(uploadParam.getCategoryIds(), uploadParam.getZzdx());
//        imageInfo.setFileName(fileName);
//        if (fileName.startsWith("500")) {
//            return fileName;
//        }
        File file = null;
        if (StringUtils.isNotBlank(uploadParam.getRealFileUrl())) {
            file = new File(uploadParam.getRealFileUrl());
        }
        if (file != null && file.exists()) {
            assignService.giveImageInfo(uploadParam, imageInfo);
        }
        if (StringUtils.isNotBlank(imageInfo.getTargetType())){
            if(imageInfoMapper.selectCountBytargetXh(imageInfo.getTargetType(),imageInfo.getId())>=maxJoinNum){
                return "400,目标关联数据超过最大限制!";
            }
        }

        imageInfoMapper.updateByPrimaryKeySelective(imageInfo);
        /**
         * 处理标签信息-删除原有标签，添加新标签
         */

        if (uploadParam.getCategoryIds() != null) {
            connectionMapper.deleteByMessageId(uploadParam.getId());
            if (uploadParam.getCategoryIds().size() > 0) {
                categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), imageInfo.getId(), 2);
            }
        }
        return "200,操作成功";
    }

    public List<TProductInfoVo> searchImage(String targetType, String imageName)
    {
        return imageInfoMapper.searchProduct(targetType, imageName);
    }



    public TImageItemVo getImageItem(Integer id) {
        return imageInfoMapper.getImageItem(id);
    }



    @Transactional(rollbackFor = Exception.class)
    public String batchUploadImage(List<ImageParam> list) {
//        List<TImageInfo> beans = new ArrayList();
//        ArrayList<String> fileNames = new ArrayList<>();
//        for (ImageParam uploadParam : list) {
//            String fileName = generatorFileName(uploadParam.getCategoryIds());
//            uploadParam.setFileName(fileName);
//            TImageInfo imageInfo = new TImageInfo();
//            BeanUtils.copyProperties(uploadParam, imageInfo);
//            /**
//             * 赋予图像媒体信息
//             */
//            giveImageInfo(uploadParam, imageInfo);
//            /**
//             * 初始化信息
//             */
//            imageInfo.setCreateDate(new Date());
//            imageInfo.setViewNumber(0L);
//            imageInfo.setDownloads(0L);
//            beans.add(imageInfo);
//            fileNames.add(imageInfo.getFileName());
//        }
//        imageInfoMapper.batchUploadImage(beans);
//        List<Integer> integers = imageInfoMapper.selectByFileNames(fileNames);
//        for (int i = 0; i < list.size(); i++) {
//            ImageParam uploadParam = list.get(i);
//            insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(),
//                    Long.parseLong(integers.get(i).toString()), 2);
//        }
        String targetType = list.get(0).getTargetType();
        if (StringUtils.isNotBlank(targetType)) {
            if (imageInfoMapper.selectCountBytargetXh(targetType, 0L) + list.size() > maxJoinNum) {
                return "400,目标关联数据超过最大限制!";
            }
        }
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                long l = System.currentTimeMillis();
                for (ImageParam uploadParam : list) {
                    uploadImage(uploadParam);
                }
                System.out.println("平均每条数据耗费时间" + ((System.currentTimeMillis() - l) / list.size()));
            }
        }).start();
        int num = 2670 * list.size() / (1000 * 60);
        if (list.size() > 23) {
            return "数据录入中!";
//            return "数据录入中，预计" + num + "分钟后录入完毕!";
        } else {
            return "数据录入中！";
//            return "数据录入中，预计" + (2670 * list.size() / 1000) + "秒后录入完毕！";
        }
    }


    public String uploadImage(ImageParam uploadParam) throws IOException {
        String fileName = uploadParam.getFileName();
        if (fileName.endsWith("****")) {
            String bm = String.format("%04d", Integer.parseInt(categoryTypeMapper.getSequence()));
            String replace = fileName.replace("****", bm);
            uploadParam.setFileName(replace);
        }
        String realFileUrl = uploadParam.getRealFileUrl();
        if (StringUtils.isBlank(realFileUrl)) {
            return "500,文件地址无效";
        }
        if (!new File(realFileUrl).exists()) {
            return "500,文件地址无效";
        }
        if (StringUtils.isNotBlank(uploadParam.getTargetType())) {
            if (imageInfoMapper.selectCountBytargetXh(uploadParam.getTargetType(), 0L) >= maxJoinNum) {
                return "400,目标关联数据超过最大限制!";
            }
        }

        /**
         * 组合ZC图像信息，保存到数据库中
         */
//        String fileName = generatorFileName(uploadParam.getCategoryIds(), uploadParam.getZzdx());
//        if (fileName.startsWith("500")) {
//            return fileName;
//        }
//        uploadParam.setFileName(fileName);
        TImageInfo imageInfo = insertImageInfo(uploadParam);
//        insertAtlasMidT(uploadParam.getAtlasIds(),imageInfo.getId(),2);
        /**
         * 将关联的标签信息保存到关联表中
         */
        if (uploadParam.getCategoryIds() != null && uploadParam.getCategoryIds().size() > 0) {
            categoryService.insertCategory(uploadParam.getCategoryIds(), uploadParam.getOperator(), imageInfo.getId(), 2);
        }
        return "200,操作成功";
    }



    private TImageInfo insertImageInfo(ImageParam uploadParam) throws IOException {
        TImageInfo imageInfo = new TImageInfo();
        BeanUtils.copyProperties(uploadParam, imageInfo);
//        imageInfo.setFileName(uploadParam.getFileName());
        /**
         * 赋予图像媒体信息
         */
        assignService.giveImageInfo(uploadParam, imageInfo);
        /**
         * 初始化信息
         */
        imageInfo.setCreateDate(new Date());
        imageInfo.setViewNumber(0L);
        imageInfo.setDownloads(0L);
//        imageInfo.setIsExamine(1);
        imageInfoMapper.insertSelective(imageInfo);
//        ArrayList<String> fileNames = new ArrayList<>();
//        fileNames.add(imageInfo.getFileName());
//        List<Integer> ids = imageInfoMapper.selectByFileNames(fileNames);
//        imageInfo.setId(Long.parseLong(ids.get(0).toString()));
        return imageInfo;

    }
}
